<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { findAllClazzApi } from '../../api/clazz'
import { cSelectAllClazzApi, addStudentApi, deleteStudentByIdApi, updateStudentByIdApi, selectStudentByIdApi, vioStudentApi } from '../../api/student'

// 对话框 添加、修改 表单数据
const studentDialogData = ref(
  {
    id: '',
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: '',
  },
)

// 对话框 违纪 表单数据
const disciplineDialogData = ref(
  {
    id: '',
    score: '',
    name: '',
  },
)

// 查询表单数据
const studentFromData = ref({
  name: '',
  degree: '',
  clazzId: '',
})

// 学历数据
const degreeData = ref([
  { label: '初中', value: 1 },
  { label: '高中', value: 2 },
  { label: '大专', value: 3 },
  { label: '本科', value: 4 },
  { label: '硕士', value: 5 },
  { label: '博士', value: 6 },
])

// 班级名称数据
const clazzData = ref([
  { name: '' },
])

// 学生表格数据
const studentsTableData = ref([{}])

let title = ref('')
let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)
let position = ref('right')
let dialogFormVisible = ref(false)
let formLabelWidth = '120px'
let selectionIds = ref([])
let vioDialogFormVisible = ref(false)

const genderData = ref([
  { label: '男', value: 1 },
  { label: '女', value: 2 },
])

const collegeData = ref([
  { label: '是', value: 1 },
  { label: '否', value: 0 },
])

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '学员姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '长度应在 2 到 10 之间', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '只能包含汉字、字母', trigger: 'blur' },
  ],
  no: [
    { required: true, message: '学号为必填项', trigger: 'blur' },
    { pattern: /^[0-9]{12}$/, message: '学号必须是12位数字', trigger: 'blur' },
  ],
  gender: [
    { required: true, message: '性别为必填项', trigger: 'change' },
  ],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入合法的手机号', trigger: 'blur' },
  ],
  idCard: [
    { required: true, message: '身份证号为必填项', trigger: 'blur' },
    { pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入合法的身份证号', trigger: 'blur' },
  ],
  isCollege: [
    { required: true, message: '是否院校学员为必填项', trigger: 'change' },
  ],
  address: [
    { required: false, message: '联系地址为选填项', trigger: 'blur' },
    { max: 100, message: '长度不能超过 100', trigger: 'blur' },
  ],
});

// 表单验证数据
const ruleFormRef = ref()


// 上面是数据
// -------------------------------------------------------------
// -------------------------------------------------------------
// -------------------------------------------------------------
// -------------------------------------------------------------
// -------------------------------------------------------------
// -------------------------------------------------------------
// 下面是函数



// 选择框选中事件
function handleSelectionChange(val) {
  selectionIds.value = val.map(student => student.id)
}
// 添加按钮事件
function addBut() {
  dialogFormVisible.value = true
  title.value = '添加学员'
}


// 
function handleSizeChange() {
  search()
}

function handleCurrentChange() {
  search()
}

// 清空查询表单数据
function clearStudentFromData() {
  studentFromData.value = {
    name: '',
    degree: '',
    clazzId: '',
  }
  search()
}

// 清空对话框表单数据
function clearStudentDialogData() {
  studentDialogData.value = {
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: '',
  }
}

// 条件分页查询学生信息
async function search() {
  const result = await cSelectAllClazzApi(studentFromData.value.name,
    studentFromData.value.degree,
    studentFromData.value.clazzId,
    currentPage.value,
    pageSize.value)

  if (result.code == 1) {
    total.value = result.data.total
    studentsTableData.value = result.data.rows
  } else {
    ElMessage.error(result.msg)
  }
}


// 查询班级名称
async function findAllClazz() {
  const result = await findAllClazzApi()
  if (result.code == 1) {
    clazzData.value = result.data
  } else {
    ElMessage.error(result.msg)
  }
}

// 对话框保存按钮事件
async function saveBut() {

  if (!ruleFormRef) return;

  await ruleFormRef.value.validate(async (valid) => { //valid 表示是否校验通过: true 通过 / false  不通过
    if (valid) { //通过
      let result;
      if (studentDialogData.value.id) {
        // 修改
        result = await updateStudentByIdApi(studentDialogData.value)
      } else {
        //添加
        result = await addStudentApi(studentDialogData.value)
      }
      if (result.code == 1) {
        ElMessage.success('操作成功')
        dialogFormVisible.value = false
        clearStudentDialogData()
        search()
      } else {
        ElMessage.error(result.msg)
      }
    } else {
      ElMessage.error('请填写正确的数据')
    }
  })


}

// 对话框取消按钮事件
function cancelBut() {
  dialogFormVisible.value = false
  clearStudentDialogData()
  search()
  ruleFormRef.value.resetFields()
}

// 违纪对话框 确定按钮事件
async function updateStudentByVio() {
  const result = await vioStudentApi(disciplineDialogData.value.id, disciplineDialogData.value.score)
  if (result.code == 1) {
    ElMessage.success('操作成功')
    vioDialogFormVisible.value = false
    disciplineDialogData.value = {
      id: '',
      score: '',
    }
    search()
  } else {
    ElMessage.error(result.msg)
  }
}

// 批量删除按钮事件
async function delBut() {
  ElMessageBox.confirm(
    '您确定要删除这些部门吗?',
    '删除部门',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      if (selectionIds.value.length == 0) {
        ElMessage.error('请选择要删除的部门')
        return
      } else {
        const result = await deleteStudentByIdApi(selectionIds.value)
        if (result.code == 1) {
          ElMessage.success('删除成功')
          search()
        } else {
          ElMessage.error(result.msg)
        }
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 学生表格 删除按钮事件
async function delTableBut(id, name) {
  ElMessageBox.confirm(
    '您确定要删除吗?',
    `删除--${name}`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteStudentByIdApi(id)
      if (result.code == 1) {
        ElMessage.success('删除成功')
        search()
        dialogFormVisible.value = false
        clearStudentDialogData()
      } else {
        ElMessage.error(result.msg)
      }
    })
}

// 学生表格 编辑按钮事件 
// Id查询学生
async function editTableBut(id) {
  title.value = '修改学员'
  const result = await selectStudentByIdApi(id)
  if (result.code == 1) {
    studentDialogData.value = result.data
  } else {
    ElMessage.error(result.msg)
  }

  dialogFormVisible.value = true

}


// 学生表格 违纪按钮事件
async function vioTableBut(id) {
  const result = await selectStudentByIdApi(id)
  if (result.code == 1) {
    disciplineDialogData.value.name = result.data.name
  } else {
    ElMessage.error(result.msg)
  }
  title.value = `违纪操作 - [${disciplineDialogData.value.name}]`
  vioDialogFormVisible.value = true
  disciplineDialogData.value.id = id

}


onMounted(() => {
  search()
  findAllClazz()
})

</script>

<template>
  <h1>学员管理</h1>

  <!-- 查询表单 -->
  <div class="container">

    <el-form :inline="true" :model="studentFromData" class="demo-form-inline">

      <el-form-item label="姓名">
        <el-input v-model="studentFromData.name" placeholder="请输入学生名称" clearable />
      </el-form-item>
      <el-form-item label="最高学历">
        <el-select v-model="studentFromData.degree" placeholder="请选择" clearable>
          <el-option v-for="(degree, index) in degreeData" :key="index" :label="degree.label" :value="degree.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属班级">
        <el-select v-model="studentFromData.clazzId" placeholder="请选择学生班级名称" clearable>
          <el-option v-for="clazz in clazzData" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
        </el-select>
      </el-form-item>

      <!-- 查询表单按钮 -->
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="info" @click="clearStudentFromData">清空</el-button>
      </el-form-item>

    </el-form>
  </div>

  <!-- {{ selectionIds }} -->
  <!-- 添加学升、批量删除 按钮 -->
  <div class="container">
    <el-button type="primary" @click="addBut"><el-icon>
        <Plus />
      </el-icon>添加学员</el-button>
    <el-button type="danger" @click="delBut"><el-icon>
        <Plus />
      </el-icon>批量删除</el-button>
  </div>

  <!-- 学生信息展示表格 -->
  <div class="container">
    <el-table class="el-table" :data="studentsTableData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="姓名" prop="name" width="80" align="center" />
      <el-table-column label="学号" prop="no" width="120" align="center" />

      <el-table-column label="班级" prop="clazzName" width="160" align="center" />

      <el-table-column label="性别" prop="gender" width="80" align="center">
        <template #default="scope">
          {{ scope.row.gender == 1 ? '男' : '女' }}
        </template>

      </el-table-column>
      <el-table-column label="手机号" prop="phone" width="120" align="center" />
      <el-table-column label="最高学历" width="120" align="center">
        <template #default="scope">
          <span v-if="scope.row.degree == 1">初中</span>
          <span v-else-if="scope.row.degree == 2">高中</span>
          <span v-else-if="scope.row.degree == 3">大专</span>
          <span v-else-if="scope.row.degree == 4">本科</span>
          <span v-else-if="scope.row.degree == 5">硕士</span>
          <span v-else-if="scope.row.degree == 6">博士</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>

      <el-table-column label="违纪次数" prop="violationCount" width="120" align="center" />
      <el-table-column label="违纪扣分" prop="violationScore" width="120" align="center" />
      <el-table-column label="最后操作时间" prop="updateTime" width="300" align="center" />
      <el-table-column label="操作" style="width: 100%;" align="center">
        <template #default="scope">
          <el-button size="small" type="primary"  @click="editTableBut(scope.row.id)">编辑</el-button>
          <el-button size="small" type="warning"  @click="vioTableBut(scope.row.id)">违纪</el-button>
          <el-button size="small" type="danger"   @click="delTableBut(scope.row.id, scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
    :background="background" layout="sizes, total, prev, pager, next, jumper" :total="total"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />


  <!-- 添加对话框 -->
  <div class="container">
    <el-dialog v-model="dialogFormVisible" :title="title" width="800">
      <el-form :rules="rules" ref="ruleFormRef" :model="studentDialogData" :label-position="position">
        <!-- 第一行 -->
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
              <el-input v-model="studentDialogData.name" placeholder="请输入姓名" autocomplete="off" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="学号" prop="no" :label-width="formLabelWidth">
              <el-input v-model="studentDialogData.no" placeholder="请输入学号" autocomplete="off" />
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第2行 -->
        <el-row :gutter="20">

          <el-col :span="12">

            <el-form-item label="性别" prop="gender" :label-width="formLabelWidth">

              <el-select v-model="studentDialogData.gender" placeholder="请选择" style="width: 100%;">
                <el-option v-for="gender in genderData" :label="gender.label" :value="gender.value" />
              </el-select>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号" prop="phone" :label-width="formLabelWidth">
              <el-input v-model="studentDialogData.phone" placeholder="请输入手机号" autocomplete="off" />
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第3行 -->
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard" :label-width="formLabelWidth">
              <el-input v-model="studentDialogData.idCard" placeholder="请输入身份证号" autocomplete="off" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否院校学员" prop="isCollege" :label-width="formLabelWidth">
              <el-select v-model="studentDialogData.isCollege" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(college, index) in collegeData" :key="index" :label="college.label"
                  :value="college.value" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第4行 -->
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="联系地址" prop="address" :label-width="formLabelWidth">
              <el-input v-model="studentDialogData.address" placeholder="请输入联系地址" autocomplete="off" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="最高学历" :label-width="formLabelWidth">
              <el-select v-model="studentDialogData.degree" placeholder="请选择" style="width: 100%;">
                <el-option v-for="(degree, index) in degreeData" :key="index" :label="degree.label"
                  :value="degree.value" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <!-- 第5行 -->
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="毕业时间" :label-width="formLabelWidth">
              <el-date-picker v-model="studentDialogData.graduationDate" type="date" placeholder="请选择毕业时间"
                value-format="YYYY-MM-DD" style="width: 100%;" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属班级" v-model="studentDialogData.clazzId" :label-width="formLabelWidth">
              <el-select v-model="studentDialogData.clazzId" placeholder="请选择班级" style="width: 100%;">
                <el-option v-for="clazz in clazzData" :key="clazz.id" :label="clazz.name" :value="clazz.id" />
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="saveBut()">保存</el-button>

            <el-button type="info" @click="cancelBut()">取消</el-button>
          </div>
        </template>
    </el-dialog>
  </div>

  <!-- 违纪对话框 -->
  <div class="container">
    <el-dialog v-model="vioDialogFormVisible" :title="title" width="600">

      <el-form :model="disciplineDialogData" :label-position="position">
        <el-form-item label="违纪扣分" :label-width="formLabelWidth">
          <el-input v-model="disciplineDialogData.score" autocomplete="off" />
        </el-form-item>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateStudentByVio">确定</el-button>
          <el-button type="info" @click="vioDialogFormVisible = false">取消</el-button>
        </div>
      </template>

    </el-dialog>
  </div>

</template>

<style scoped>
.container {
  margin-top: 20px;
}

/* 表格边框加粗 - 使用更明显的颜色和宽度 */
:deep(.el-table) {
  border: 2px solid #d1d5da !important;
}

/* 加粗表格内部边框 - 使用更明显的颜色和宽度 */
:deep(.el-table td),
:deep(.el-table th) {
  border: 1px solid #dbe0e4 !important;
}

/* 表头边框可以更粗一些 */
:deep(.el-table th) {
  background-color: #eaebee !important;
  border-bottom: 2px solid #dee2e6 !important;
}
</style>